package com.gzcstec.order.convert;

import com.fasterxml.jackson.core.type.TypeReference;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gzcstec.order.dataobject.OrderDetail;
import com.gzcstec.order.dto.OrderDTO;
import com.gzcstec.order.enums.ExceptionCodeEnums;
import com.gzcstec.order.exception.OrderException;
import com.gzcstec.order.form.OrderForm;
import com.gzcstec.order.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class OrderFormConvertOrderDTO {

    private OrderFormConvertOrderDTO(){}

    public static OrderDTO convert(OrderForm orderForm) {
        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setBuyerAddress(orderForm.getAddress());
        orderDTO.setBuyerName(orderForm.getName());
        orderDTO.setBuyerOpenid(orderForm.getOpenid());
        orderDTO.setBuyerPhone(orderForm.getPhone());

        List<OrderDetail> orderDetailList = new ArrayList<>();

        try {
            //捕捉转换出错情况
            orderDetailList = JsonUtils.fromJson(orderForm.getItems(),
                    new TypeToken<List<OrderDetail>>() {});
//            Gson gson = new Gson();
//            orderDetailList = gson.fromJson(orderForm.getItems()
//                    , new TypeToken<List<OrderDetail>>(){}.getType());
        }catch (Exception e) {
            log.error("【订单创建】购物车转换错误，orderForm={}" , orderForm);
            throw new OrderException(ExceptionCodeEnums.PARAM_ERROR);
        }
        orderDTO.setOrderDetailList(orderDetailList);
        return orderDTO;
    }
}
